package com.apes.fn.pi.scan;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.server.productReceive.ProductReceive;
import com.apes.fn.server.productReceive.ProductReceiveItem;
import com.apes.fn.server.servicePlan.model.ServicePlanItem;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import com.apes.scm.stock.inventory.model.InventoryMark;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by lishikun on 2020/12/9 9:11
 */
@Service("piScanService")
public class piScanService extends DomainService {

    /**
     * 主表
     * [{"locationId" "仓库编码"  "CKKQID",
     *  "receiverId"   "领料人"
     *
     *  "servicePlanId"       "服务单号"  ,
     *
     *  items : [{"companyId" ："公司编码"，"productId"： "商品编码", "qty" : "扫码件数"， "", "servicePlanItemId" : "服务方案明细编码" }, {}]
     *
     * }]
     *
     *
     */
    @Autowired
    LocationRepository locationRepository;

    public JSONArray scanSubmit(SimpleRequest request) {
        JSONArray requestJA = request.getJO().getJSONArray("data");
        JSONArray jsonArray = formatScan(requestJA);
        return saveScan(jsonArray);
    }

    private JSONArray saveScan(JSONArray request) {
        JSONArray array = request;
        JSONArray response = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        for (int i = 0; i < array.size(); i++) {
            JSONObject tempJson = array.getJSONObject(i);
            String ProductReceiveId = submitProcess(tempJson);
            jsonObject.put("productReceiveId",ProductReceiveId);
            jsonObject.put("servicePlanId",tempJson.getString("servicePlanId"));
            response.add(jsonObject);
        }
        return response;
    }


    private String submitProcess(JSONObject json){
        if (StringUtils.isEmpty(json.getString("locationId"))) { throw new RuntimeException("仓库编码不能为空"); }

        ProductReceive productReceive = new ProductReceive();
        productReceive.setReceiver(getCreator(json.getString("receiverId")));
        Location location = locationRepository.findOne(json.getString("locationId"));
        if (location == null) throw new RuntimeException("未找到仓库信息");
        productReceive.setLocation(location);
        productReceive.setSource(json.getString("servicePlanId"));
        productReceive.setSourceBusinessType("ServicePlan");
        productReceive.setSourceBusinessTypeName("服务方案");
        productReceive.setScanSign(true); //设置扫码标记
        productReceive.setRemark("APP扫码领用");
        productReceive.setState("create");

        productReceive.setProductReceiveItems(((JSONArray) json.get("items")).stream().map(ly -> {
            JSONObject receive = (JSONObject) ly;
            ProductReceiveItem productReceiveItem = new ProductReceiveItem();
            PartyRole company = SpringManager.getBean(PartyRoleRepository.class).findOne((receive.getString("companyId")));
            if ( company == null )
                throw new RuntimeException("找不到对应的公司!!!");
            productReceiveItem.setCompany(company);
            productReceive.setCompany(productReceiveItem.getCompany());
            productReceiveItem.setProduct(getProduct(receive.getString("productId")));
            productReceiveItem.setUom(productReceiveItem.getProduct().getUom());
            productReceiveItem.setQtyReceive(receive.getDouble("qty"));

            // 与原服务方案明细做关联
            ServicePlanItem servicePlanItem = new ServicePlanItem();
            servicePlanItem.setId(receive.getString("servicePlanItemId"));
            productReceiveItem.setServicePlanItem(servicePlanItem);
            return productReceiveItem;
        }).collect(Collectors.toList()));
        ProductReceive receive = invoke("stock.productReceive.create", MapUtil.mapped(productReceive));
        invoke("stock.productReceive.approve", MapUtil.mapped(receive));
        return receive.getId();
    }

    private PartyRole getCreator(String userId) {
        User user = SpringManager.getBean(UserRepository.class).findByOrigin(userId);
        if (user == null) throw new RuntimeException("未找到操作员信息！");
        return user.getPerson();
    }

    public Product getProduct(String origin) {
        Product product = SpringManager.getBean(ProductRepository.class).findOne(origin);
        if (product == null) throw new RuntimeException("商品信息不存在！外部编码：" + origin);
        return product;
    }

    // APP传过的数据进行转化结构
    public JSONArray formatScan(JSONArray array) {

        Map<String, Map> servicePlans = new HashMap();
        array.stream().collect(Collectors.groupingBy(v -> {
            JSONObject temp = (JSONObject) v;
            return temp.getString("servicePlanId");
        })).forEach( (indexKey, list) -> {
            servicePlans.put(indexKey,list.stream().collect(Collectors.groupingBy(v -> {
                JSONObject temp = (JSONObject) v;
                return temp.getString("locationId");
            })));

        });
        JSONArray scanArray = new JSONArray();
        servicePlans.forEach( (servicePlanId, location) -> {
            Map<String, List<JSONObject>> locationMap = (Map)location;
            locationMap.forEach((locationId, product) ->{
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("servicePlanId", servicePlanId);
                jsonObject.put("locationId", locationId);
                jsonObject.put("receiverId", product.get(0).getString("receiverId"));
                jsonObject.put("items", JSONArray.parseArray(JSON.toJSONString(product)));
                scanArray.add(jsonObject);
            });
        });
        return scanArray;
    }


}
